import React from 'react';

import Header from '../common/Header';
import CKModal from '../components/CKModal';
import Validate from '../common/Validate';

import {
    Button,
    Input,
    Form,
    Selected
} from 'amazeui-react';

import Fetch from '../common/Fetch';

import $ from 'jquery';
class LinkManageEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {
                link_id: '',
                ctg_id: '',
                ctg_name: '',
                link_addr: '',
                link_type: '1',
                link_img: '',
                link_img_width: '50',
                link_img_height: '50'
            },
            category_data: [],
            types: [
                {label: '图片', value: '1'},
                {label: '文字', value: '2'}
            ],
            is_save: false,
            type: this.props.params.id ? 'edit' : 'add',
            is_upload: false,
            upload_img: '',
        }
        this.file = null
    }

    componentDidMount() {
        if (this.state.type == 'edit') {
            this.loadLink();
        }
        this.loadCategory();
    }

    loadLink() {
        Fetch('/cms/link_manage/link_info', {cipher_id: this.props.params.id}, (res)=> {
            if (res.status) {
                let data = this.state.data;
                $.map(res.data, (item, index)=> {
                    data[index] = item;
                })
                this.setState({
                    data: data
                });
            }
        });
    }

    loadCategory() {
        Fetch('/cms/link_manage/query_category', {
            query: {},
            num: 100,
            page: 1
        }, (res)=> {
            if (res.status) {
                let data = [];
                $.map(res.data.data, (item)=> {
                    data.push({label: item.ctg_name, value: item.ctg_id})
                });
                this.setState({
                    category_data: data
                });
            } else {
                this.modal.alert('失败', '获取友情链接分类列表出错！' + res.msg);
            }
        });
    }

    changeHandler(field) {
        return (e)=> {
            let info = this.state.data;
            let upload_img = this.state.upload_img;
            if (field == 'link_type') {
                info[field] = e;
            } else if (field == 'ctg_id') {
                $.map(this.state.category_data, (item)=> {
                    if (item.value == e) {
                        info['ctg_name'] = item.label;
                    }
                })
                info[field] = e;
            } else if(field == 'link_img_width' || field == 'link_img_height'){
                 upload_img = '';
                info[field] = e.target.value;
            }else {
                info[field] = e.target.value;
            }
            this.setState({
                data: info,
                upload_img:upload_img
            });
        }
    }

    checkData() {
        let valid = {
            link_name: {role: '*', errmsg: '链接名称不能为空'},
            ctg_name: {role: '*', errmsg: '分类不能为空'},
            link_addr: {role: '*', errmsg: '链接地址不能为空'},
        }

        let data = this.state.data;
        if (this.state.upload_img != '') {
            data['link_img'] = this.state.upload_img;
        }
        try {
            Validate.inst().checkData(data, valid);
            return data;
        } catch (e) {
            this.modal.alert('错误', e);
            return false;
        }
    }

    uploadImg = ()=> {
        if (!this.file) {
            var self = this;
            this.file = $('<input type="file"/>');
            this.file.on('change', function (e) {
                self.modal.load('正在读取图片...');
                lrz(this.files[0], {width: self.state.data.link_img_width, height: self.state.data.link_img_height, quality: .9})
                    .then((rst)=> {
                        $('#head_img').attr('src', rst.base64);
                        self.setState({
                            is_upload: true
                        });
                        self.modal.load('正在上传图片...');
                        Fetch('/cms/article_manage/upload_img',
                            {base: rst.base64},
                            (res)=> {
                                self.modal.closeModal();
                                if (res.status) {
                                    self.setState({
                                        is_upload: false,
                                        upload_img: res.data
                                    });
                                }
                            }
                        );
                    })
                    .catch((err)=> {
                        self.modal.closeModal('上传图片出错!:' + err);
                    }).always(()=> {
                    this.file.value = '';
                });
            });
        }
        this.file.click();
    };

    save = ()=> {
        let data = this.checkData();
        if (data === false || this.state.is_save) return;
        if(data.link_type == 1 && data.link_img == ''){
            this.modal.alert('错误','图片不能为空');
            return;
        }
        this.setState({
            is_save: true
        });
        console.log(data)
        Fetch('/cms/link_manage/save_link', {data: data}, (res)=> {
            if (res.status) {
                this.modal.alert('成功', '保存分类成功!', ()=> {
                    this.context.router.goBack();
                });
            } else {
                this.modal.alert('失败', '保存分类失败!!');
                this.setState({
                    is_save: false
                });
            }
        }, ()=> {
            this.modal.alert('失败', '远程调用失败!!');
            this.setState({
                is_save: false
            });
        });
    }


    render() {
        let data = this.state.data;
        return (
            <div className="content">
                <Header title={this.state.type === 'edit' ? '修改友情链接' : '添加友情链接'} back={true}/>
                <div className="content_main">
                    <div style={{marginBottom: '20px'}}>
                        <h4 className="title">链接信息</h4>
                    </div>
                    <Form ref="from" horizontal style={{marginTop: '20px'}}>

                        <Input ref="link_name" label="链接名称"
                               labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.link_name}
                               placeholder="请输入链接名称"
                               onChange={this.changeHandler('link_name')}
                        />
                        <Input ref="link_addr" label="外链地址"
                               labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.link_addr}
                               placeholder="请输入外链地址"
                               onChange={this.changeHandler('link_addr')}
                        />
                        <div className="am-form-group">
                            <label className="am-u-sm-2 am-form-label">
                                链接分类
                            </label>
                            <div className="am-u-sm-4  am-u-end">
                                <Selected onChange={this.changeHandler('ctg_id')}
                                          ref="ctg_name"
                                          placeholder="请选择分类"
                                          data={this.state.category_data}
                                          value={data.ctg_id || ''}/>
                            </div>
                        </div>
                        <div className="am-form-group">
                            <label className="am-u-sm-2 am-form-label">
                                链接类型
                            </label>
                            <div className="am-u-sm-4  am-u-end">
                                <Selected onChange={this.changeHandler('link_type')}
                                          placeholder="请选择类型"
                                          data={this.state.types}
                                          value={data.link_type || ''}/>
                            </div>
                        </div>

                        <div className="am-form-group"
                             style={{display: this.state.data.link_type == 1 ? 'block' : 'none'}}>
                            <div className="am-u-sm-2">
                                &nbsp;
                            </div>
                            <div className="am-u-sm-4 am-u-end">
                                <img id="head_img" src={data.link_img || require('../assets/img/default_head.jpg')}
                                     style={{width:data.link_img_width,height:data.link_img_height}}
                                     className="header_img"/>
                                <Button style={{marginLeft: '20px'}}
                                        amStyle="secondary"
                                        disabled={this.state.is_upload}
                                        onClick={this.uploadImg}>

                                    {this.state.is_upload ? '上传中...' : '上传'}
                                </Button>
                            </div>
                        </div>
                        <div style={{display: this.state.data.link_type == 1 ? 'block' : 'none'}}>
                            <Input ref="link_img_width" label="图片宽度" type="number"
                                   labelClassName="am-u-sm-2"
                                   wrapperClassName="am-u-sm-4 am-u-end"
                                   value={data.link_img_width}
                                   placeholder="请输入图片宽度"
                                   onChange={this.changeHandler('link_img_width')}
                            />
                            <Input ref="link_img_height" label="图片高度" type="number"
                                   labelClassName="am-u-sm-2"
                                   wrapperClassName="am-u-sm-4 am-u-end"
                                   value={data.link_img_height}
                                   placeholder="请输入图片高度"
                                   onChange={this.changeHandler('link_img_height')}
                            />
                        </div>

                    </Form>
                    <div className="am-form-group">
                        <div className="am-u-sm-2">
                            &nbsp;
                        </div>
                        <div className="am-u-sm-4 am-u-end">
                            <Button amStyle="primary"
                                    onClick={this.save}
                                    disabled={this.state.is_save}
                                    radius
                            >
                                {this.state.is_save ? '保存中...' : '保存'}
                            </Button>
                        </div>
                    </div>
                </div>
                <CKModal ref={(c)=> {
                    this.modal = c
                }}/>
            </div>
        );
    }
}
LinkManageEdit.contextTypes = {
    router: React.PropTypes.object
}
export default LinkManageEdit;